﻿using Infragistics.Win.UltraWinGrid;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Titan.FIS.Barcode.TwoBarcode;
using Titan.FIS.Enum;
using Titan.FIS.UI;
using Titan.WinFormSys;
using Titan.WinFormSys.Entity;

namespace Titan.FIS.SampleRecd
{
    public partial class frmMmsMain : FrmBase
    {
        private readonly IList<UltraGridRow> _listSelectRow = new List<UltraGridRow>();//选中的设备，用于打印

        private string _strBatchCode = string.Empty;

        //是否打印标签数字
        private int _iPrintTestCodeNum = 0;
        //是否自动打印试样编码
        private int _iAutoPrintSampleCode = 0;
        //打印条码类型
        private int _iPrintBarcodeType = 2;

        /// <summary>
        /// 当前化验室
        /// </summary>
        private LaboratoryType _LabType = LaboratoryType.RL;
        /// <summary>
        /// 构造函数
        /// </summary>
        public frmMmsMain()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 初始化函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMain_Load(object sender, EventArgs e)
        {
            dtDate.Value = DateTime.Now;

            Common.UserInfo = UserInfo;
            Common.MsgBox = ricMsg;

            string strLmsLabType = System.Configuration.ConfigurationManager.AppSettings["LMS_LAB"];

            if (strLmsLabType == "RC")
            {
                _LabType = LaboratoryType.RC;
            }

            try
            {
                _iPrintTestCodeNum = int.Parse(ConfigurationManager.AppSettings["PrintTestCodeNum"]);
                _iAutoPrintSampleCode = int.Parse(ConfigurationManager.AppSettings["AutoPrintSampleCode"]);
                _iPrintBarcodeType = int.Parse(ConfigurationManager.AppSettings["PrintBarcodeType"]);
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取RFID读卡器配置信息失败,请检查配置文件!" + ex.Message);
            }
        }

        /// <summary>
        /// 表格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridMain_Click(object sender, EventArgs e)
        {
            if (GridMain.ActiveRow != null)
            {
                try
                {
                    GridMain.ActiveRow.Cells["CHECK"].Value = !(bool)GridMain.ActiveRow.Cells["CHECK"].Value;
                    if ((bool)GridMain.ActiveRow.Cells["CHECK"].Value)
                    {
                        _listSelectRow.Add(GridMain.ActiveRow);
                    }
                    else
                    {
                        _listSelectRow.Remove(GridMain.ActiveRow);
                    }
                }
                catch//默认值不是有效的布尔值，故会异常，也就是第一次选择，即设置为真
                {
                    GridMain.ActiveRow.Cells["CHECK"].Value = true;
                    _listSelectRow.Add(GridMain.ActiveRow);
                }
                GridMain.ActiveRow.Activated = false;
            }
        }

        /// <summary>
        /// RFID输入框点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtRFID_Click(object sender, EventArgs e)
        {
            txtRFID.Text = "";
        }

        /// <summary>
        /// 按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ultraToolbarsManager1_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            switch (e.Tool.Key.ToString())
            {
                case "PasteCode":
                    DoPasteCode();
                    break;
                case "SubSample":
                    var objSub = new frmReceiveSample(_iPrintBarcodeType);
                    objSub.ShowDialog();
                    break;
                case "Query":
                    DoQuery("Normal");
                    break;
                case "Read":
                    DoRead();
                    break;
                case "Write":
                    DoWrite();
                    break;
                case "Add":
                    DoAdd();
                    break;
                case "btnAddBatch":
                    DoAddBatch();
                    break;
                case "RandomSample":
                    DoRandomSample();
                    break;
                case "Delete":
                    DoDelete();
                    break;
                case "Print":
                    DoPrintView();
                    break;
                case "PrintAll":
                    DoPrintAll();
                    break;
                case "PrintCode":
                    DoPrintCode();
                    break;
                case "PrintMt":
                    DoAddMt();
                    break;
                case "SelfSample":
                    var objSelf = new frmSelfSample();
                    objSelf.ShowDialog();
                    break;
            }
        }

        private void DoPasteCode()
        {
            var code = Clipboard.GetText();
            try
            {
                var tmp = int.Parse(code.ToString()); if (tmp <= 0 || (code.Length != 7 && code.Length != 8))
                    return;
                txtCode.Text = code;
            }
            catch { }
        }

        /// <summary>
        /// 查询
        /// </summary>
        private void DoQuery(string QueryType)
        {
            _listSelectRow.Clear();

            DataTable tabSource = null;
            string strDateTime = string.Empty;
            if (dtDate.Checked)
                strDateTime = dtDate.Value.ToString("yyyy-MM-dd");
            var errMsg = DataOperate.DataQuery.DoQuerySampleInfo(strDateTime, txtCode.Text, txtRFID.Text, cbType.Text, _LabType, ref tabSource);
            if (string.IsNullOrEmpty(errMsg))
            {
                tabSource.Columns.Add("CHECK", typeof(bool));
                tabSource.Columns["CHECK"].ReadOnly = false;
                Titan.FIS.Data.MergeDataTable.MergeCaption(tabMain, ref tabSource);
                GridMain.DataSource = tabSource;
                if (QueryType == "Normal")
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Run, "查询已完成！请在表格中查看相关数据");
            }
            else
            {
                GridMain.DataSource = tabMain;
                if (QueryType == "Normal")
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("查询失败，原因:{0}", errMsg));
            }
        }


        /// <summary>
        /// 读卡
        /// </summary>
        private void DoRead()
        {
            txtRFID.Text = "";
        }

        /// <summary>
        /// 启动读卡
        /// </summary>
        private bool DoReadRfid(ref string strRfid)
        {
            var bSuccess = false;
            return bSuccess;
        }

        /// <summary>
        /// 写卡
        /// </summary>
        /// <returns></returns>
        private void DoWrite()
        {
        }


        /// <summary>
        /// 启动写卡
        /// </summary>
        /// <returns></returns>
        private bool DoWriteRfid(string strContent)
        {
            var bSuccess = false;
            return bSuccess;
        }
        /// <summary>
        /// 启动写卡
        /// </summary>
        /// <returns></returns>
        private bool DoWriteRfid(byte[] bytesContent)
        {
            var bSuccess = false;
            return bSuccess;
        }

        /// <summary>
        /// 添加
        /// </summary>
        private void DoAdd()
        {
            if (string.IsNullOrEmpty(txtCode.Text.Trim()))
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "请输入收样编码!");
                return;
            }

            var strMode = string.Empty;//隐式制样方式，0:收样编码，1:批次编码，2人工采样编码，6制样编码
            try
            {
                int i; int.TryParse(txtCode.Text.Trim(), out i);
                if (txtCode.Text.Trim().Length < 3)
                {
                    strMode = "0";
                }
                else if (txtCode.Text.Trim().Length == 8)
                {
                    strMode = "1";
                }
                else if (txtCode.Text.Trim().Length == 6)
                {
                    strMode = "2";
                }
                else if (txtCode.Text.Trim().Length == 7)
                {
                    strMode = "6";
                }
                else
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "编码输入错误，请重新输入");
                    return;
                }
            }
            catch
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "编码输入异常，请重新输入!");
                return;
            }

            if (string.IsNullOrEmpty(cbType.Text) || cbType.Text == " ")
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "请选择样品类型!");
                return;
            }

            var strType = string.Empty;//0.2mm 数据库用
            switch (cbType.Text)
            {
                case "13mm水分":
                    strType = "20";//13mm
                    break;
                case "1.5mmY":
                    strType = "21";//1.5mm
                    break;
                case "1mm岩相":
                    strType = "22";//1mm
                    break;
                case "0.425mm流动":
                    strType = "23";//0.45mm
                    break;
                case "0.2mm工分":
                    strType = "24";//0.2mm工
                    break;
                case "0.2mmb":
                    strType = "25";//0.2bmm
                    break;
                case "0.2mmG":
                    strType = "26";//0.2Gmm
                    break;
                case "0.2mm热值":
                    strType = "27";//0.2Gmm热
                    break;
                case "25mmCSR":
                    strType = "28";//25mmCSR
                    break;
                case "3mmTOD":
                    strType = "29";//3mmTOD
                    break;
            }
            if (string.IsNullOrEmpty(strType))
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "请选择样品类型!");
                return;
            }

            var strQuerstion = string.Format("请确认是否添加收样编码【{0}】下【{1}】试样一份？", txtCode.Text.Trim(), cbType.Text.Trim());
            if (MessageBox.Show(strQuerstion, "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var strSampleCode = string.Empty;
                var strErrInfo = string.Empty;
                var strLmsReceive = "0";
                var strSampleNum = "0";
                var samleNum = 0;
                var bCheckResult = DataOperate.DataExecProc.DoCheckSample(txtCode.Text.Trim(), strType, strMode, ref strSampleNum, ref strLmsReceive, ref strErrInfo);
                if (!bCheckResult)
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("检查收样编码失败,原因:{0}", strErrInfo));
                    return;
                }
                else
                {
                    try
                    {
                        samleNum = int.Parse(strSampleNum);
                    }
                    catch
                    {
                        FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("检查同类型样品数量失败,数量为:{0}", strSampleNum));
                        return;
                    }
                    if (samleNum > 0)
                    {
                        if (strLmsReceive == "1")
                        {
                            if (MessageBox.Show(string.Format("收样编码【{0}】下【{1}】试样已存在【{2}】份,且已被化验室收样，请检查编码是否录入错误！请确认是否继续添加？", txtCode.Text.Trim(), cbType.Text.Trim(), samleNum), "！！！告警信息！！！", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                            {
                                return;
                            }
                        }
                        else
                        {
                            if (MessageBox.Show(string.Format("收样编码【{0}】下【{1}】试样已存在【{2}】份,请确认是否继续添加？", txtCode.Text.Trim(), cbType.Text.Trim(), samleNum), "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                            {
                                return;
                            }
                        }
                    }
                }

                var bSaveResult = DataOperate.DataExecProc.DoAddSample(txtCode.Text.Trim(), txtRFID.Text.Trim(), strType, strMode, ref strSampleCode, ref strErrInfo);
                if (!bSaveResult)
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("添加试样编码失败,原因:{0}", strErrInfo));
                }
                else
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Run, string.Format("添加试样编码《{0}》成功!", strSampleCode));
                    if (_iAutoPrintSampleCode == 1)
                        DoPrint(txtCode.Text.Trim(), strSampleCode, cbType.Text.Trim());
                    //txtCode.Text = "";
                    txtRFID.Text = "";
                    dtDate.Value = DateTime.Now;
                    dtDate.Checked = true;

                    DoQuery("ADD");
                }
            }
        }

        private void DoAddBatch()
        {
            if (string.IsNullOrEmpty(txtCode.Text.Trim()))
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "请输入收样编码!");
                return;
            }

            var strMode = string.Empty;
            try
            {
                int i; int.TryParse(txtCode.Text.Trim(), out i);
                if (txtCode.Text.Trim().Length < 3)
                {
                    strMode = "0";
                }
                else if (txtCode.Text.Trim().Length == 8)
                {
                    strMode = "1";
                }
                else if (txtCode.Text.Trim().Length == 6)
                {
                    strMode = "2";
                }
                else if (txtCode.Text.Trim().Length == 7)
                {
                    strMode = "6";
                }
                else
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "编码输入错误，请重新输入");
                    return;
                }
            }
            catch
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "编码输入异常，请重新输入!");
                return;
            }
            var strQuerstion = string.Format("请确认是否添加收样编码【{0}】下需要制样的所有试样编码？", txtCode.Text.Trim());
            if (MessageBox.Show(strQuerstion, "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            DataTable tabSourceMateriel = null;
            var errMsg = DataOperate.DataQuery.DoQueryMateriel(strMode, txtCode.Text.Trim(), ref tabSourceMateriel);
            if (!string.IsNullOrEmpty(errMsg))
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, errMsg);
                return;
            }
            Dictionary<SampleType, string> dtSampleType = new Dictionary<SampleType, string>();
            if (tabSourceMateriel.Rows[0]["BATCH_TYPE"].ToString() == "入厂煤" || strMode == "0")
            {
                dtSampleType.Add(SampleType.S13mm全水, "");
                dtSampleType.Add(SampleType.S0_2mm工分, "");
                if (tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "动力煤") //动力煤 化工煤
                {
                    dtSampleType.Add(SampleType.S0_2mm热值, "");
                }
                else
                {
                    dtSampleType.Add(SampleType.S0_2mmG, "");
                    dtSampleType.Add(SampleType.S1_5mmY, "");
                    dtSampleType.Add(SampleType.S0_2mmb, "");
                }
                var date = "";
                if (!string.IsNullOrEmpty(tabSourceMateriel.Rows[0]["RECEIVE_TIME"].ToString()))
                {
                    date = DateTime.Parse(tabSourceMateriel.Rows[0]["RECEIVE_TIME"].ToString()).ToString("yyMMdd");
                }
                DoPrintCode(date + "-" + txtCode.Text.Trim() + "-主", tabSourceMateriel.Rows[0]["MAKE_CODE"].ToString());
                DoPrintCode(date + "-" + txtCode.Text.Trim() + "-备1", tabSourceMateriel.Rows[0]["MAKE_CODE"].ToString());
                DoPrintCode(date + "-" + txtCode.Text.Trim() + "-备2", tabSourceMateriel.Rows[0]["MAKE_CODE"].ToString());
            }
            else
            {
                if (tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "槽煤" || tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "外样煤")
                {
                    dtSampleType.Add(SampleType.S13mm全水, "");
                    dtSampleType.Add(SampleType.S0_2mm工分, "");
                }
                else if (tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "煤场煤" || tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "火车煤"
                         || tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "自检煤" || tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "配合煤")
                {
                    dtSampleType.Add(SampleType.S13mm全水, "");
                    dtSampleType.Add(SampleType.S0_2mm工分, "");
                    dtSampleType.Add(SampleType.S0_2mmG, "");
                    dtSampleType.Add(SampleType.S1_5mmY, "");
                    dtSampleType.Add(SampleType.S0_2mmb, "");
                }
                else if (tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "小焦炉煤")
                {
                    dtSampleType.Add(SampleType.S13mm全水, "");
                    dtSampleType.Add(SampleType.S0_2mm工分, "");
                    dtSampleType.Add(SampleType.S0_2mmG, "");
                }
                else if (tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "小焦炉焦炭" || tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "外样焦炭" ||
                    tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "自检焦炭" || tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "出厂焦炭")
                {
                    dtSampleType.Add(SampleType.S13mm全水, "");
                    dtSampleType.Add(SampleType.S0_2mm工分, "");
                    dtSampleType.Add(SampleType.S25mmCSR, "");
                }
                else
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "未配置自动生成模板，请手动生成");
                    return;
                }
                DoPrintCode(txtCode.Text.Trim() + "-主", txtCode.Text.Trim());
                if (tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "火车煤" || tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "煤场煤" ||
                    tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "小焦炉煤")
                {
                    DoPrintCode(txtCode.Text.Trim() + "-备1", txtCode.Text.Trim());
                    DoPrintCode(txtCode.Text.Trim() + "-备2", txtCode.Text.Trim());
                }
                else if (tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "自检煤" || tabSourceMateriel.Rows[0]["MATERIEL_TYPE_NAME"].ToString() == "配合煤")
                {
                    DoPrintCode(txtCode.Text.Trim() + "-备1", txtCode.Text.Trim());
                }
            }
            foreach (var dtKey in dtSampleType.Keys)
            {
                var strType = string.Empty;//数据库用
                switch (dtKey)
                {
                    case SampleType.S13mm全水:
                        var strHCode = string.Empty;
                        var strMtErrInfo = string.Empty;
                        strType = ((int)SampleType.S13mm全水).ToString();
                        var bMtSaveResult = DataOperate.DataExecProc.DoAddSampleMt(txtCode.Text.Trim(), strType, strMode, ref strHCode, ref strMtErrInfo);
                        if (!bMtSaveResult)
                        {
                            FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("查询水分化验编码失败,原因:{0}", strMtErrInfo));
                            return;
                        }
                        else
                        {
                            DoPrintMt(txtCode.Text.Trim(), strHCode);
                        }
                        continue;
                    case SampleType.S1_5mmY:
                        strType = ((int)SampleType.S1_5mmY).ToString();
                        break;
                    case SampleType.S1mm岩相:
                        strType = ((int)SampleType.S1mm岩相).ToString();
                        break;
                    case SampleType.S0_425mm流动:
                        strType = ((int)SampleType.S0_425mm流动).ToString();
                        break;
                    case SampleType.S0_2mm工分:
                        strType = ((int)SampleType.S0_2mm工分).ToString();
                        break;
                    case SampleType.S0_2mmb:
                        strType = ((int)SampleType.S0_2mmb).ToString();
                        break;
                    case SampleType.S0_2mmG:
                        strType = ((int)SampleType.S0_2mmG).ToString();
                        break;
                    case SampleType.S0_2mm热值:
                        strType = ((int)SampleType.S0_2mm热值).ToString();
                        break;
                    case SampleType.S25mmCSR:
                        strType = ((int)SampleType.S25mmCSR).ToString();
                        break;
                    case SampleType.S3mmTOD:
                        strType = ((int)SampleType.S3mmTOD).ToString();
                        break;
                    default:
                        break;
                }
                if (string.IsNullOrEmpty(strType))
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "样品类型无效!");
                    return;
                }

                var strSampleCode = string.Empty;
                var strErrInfo = string.Empty;
                var strLmsReceive = "0";
                var strSampleNum = "0";
                var samleNum = 0;
                var bCheckResult = DataOperate.DataExecProc.DoCheckSample(txtCode.Text.Trim(), strType, strMode, ref strSampleNum, ref strLmsReceive, ref strErrInfo);
                if (!bCheckResult)
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("检查收样编码失败,原因:{0}", strErrInfo));
                    return;
                }
                else
                {
                    try
                    {
                        samleNum = int.Parse(strSampleNum);
                    }
                    catch
                    {
                        FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("检查同类型样品数量失败,数量为:{0}", strSampleNum));
                        return;
                    }
                    if (samleNum > 0)
                    {
                        if (strLmsReceive == "1")
                        {
                            if (MessageBox.Show(string.Format("收样编码【{0}】下【{1}】试样已存在【{2}】份,且已被化验室收样，请检查编码是否录入错误！请确认是否继续添加？", txtCode.Text.Trim(), EnumDescription.GetDescription(dtKey), samleNum), "！！！告警信息！！！", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                            {
                                return;
                            }
                        }
                        else
                        {
                            if (MessageBox.Show(string.Format("收样编码【{0}】下【{1}】试样已存在【{2}】份,请确认是否继续添加？", txtCode.Text.Trim(), EnumDescription.GetDescription(dtKey), samleNum), "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                            {
                                return;
                            }
                        }
                    }
                }

                var bSaveResult = DataOperate.DataExecProc.DoAddSample(txtCode.Text.Trim(), txtRFID.Text.Trim(), strType, strMode, ref strSampleCode, ref strErrInfo);
                if (!bSaveResult)
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("添加试样编码失败,原因:{0}", strErrInfo));
                    return;
                }
                else
                {
                    if (_iAutoPrintSampleCode == 1)
                        DoPrint(txtCode.Text.Trim(), strSampleCode, EnumDescription.GetDescription(dtKey));
                }

            }

            FormHelper.ApplicationShow(ricMsg, DisplayType.Run, string.Format("添加收样编码【{0}】下所有试样成功!", txtCode.Text.Trim()));

            txtCode.Text = "";
            txtRFID.Text = "";
            dtDate.Value = DateTime.Now;
            dtDate.Checked = true;
            DoQuery("ADD");
        }

        /// <summary>
        /// 添加
        /// </summary>
        private void DoAddMt()
        {
            if (string.IsNullOrEmpty(txtCode.Text.Trim()))
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "请输入收样编码!");
                return;
            }

            var strMode = string.Empty;
            try
            {
                int i; int.TryParse(txtCode.Text.Trim(), out i);
                if (txtCode.Text.Trim().Length < 3)
                {
                    strMode = "0";
                }
                else if (txtCode.Text.Trim().Length == 8)
                {
                    strMode = "1";
                }
                else if (txtCode.Text.Trim().Length == 6)
                {
                    strMode = "2";
                }
                else if (txtCode.Text.Trim().Length == 7)
                {
                    strMode = "6";
                }
                else
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "收样编码输入错误，请重新输入");
                    return;
                }
            }
            catch
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "收样编码输入异常，请重新输入!");
                return;
            }

            var strType = "20";//13mm
            var strQuerstion = string.Format("请确认是否打印收样编码【{0}】的水分化验编码？", txtCode.Text.Trim());
            if (MessageBox.Show(strQuerstion, "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var strHCode = string.Empty;
                var strErrInfo = string.Empty;

                var bSaveResult = DataOperate.DataExecProc.DoAddSampleMt(txtCode.Text.Trim(), strType, strMode, ref strHCode, ref strErrInfo);
                if (!bSaveResult)
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("查询水分化验编码失败,原因:{0}", strErrInfo));
                }
                else
                {
                    DoPrintMt(txtCode.Text.Trim(), strHCode);

                    //txtCode.Text = "";
                    dtDate.Value = DateTime.Now;
                    dtDate.Checked = true;
                    DoQuery("ADD");
                }
            }
        }
        /// <summary>
        /// 抽查样
        /// </summary>
        private void DoRandomSample()
        {

            ultraToolbarsManager1.Enabled = false;
        }

        /// <summary>
        /// 删除
        /// </summary>
        private void DoDelete()
        {
            // 已添加未打印的样品信息可以删除
            if (_listSelectRow.Count < 1)
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "请在查询出来的数据表中，勾选需要删除的行在点击删除按钮，谢谢！");
                return;
            }

            foreach (var row in _listSelectRow)
            {
                var strSampleCode = row.Cells["SAMPLE_CODE"].Value.ToString();
                var strSampleWeight = row.Cells["WEIGHT"].Value.ToString();
                var iPrintCount = int.Parse(row.Cells["PRINT_COUNT"].Value.ToString());
                if (iPrintCount > 0)
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("删除试样编码{0}失败！原因：已打印过样品标签的样品信息无法删除", strSampleCode));
                    continue;
                }
                if (!string.IsNullOrEmpty(strSampleWeight))
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("删除试样编码{0}失败！原因：已称重过的样品信息无法删除", strSampleCode));
                    continue;
                }

                var strErrInfo = string.Empty;
                var bSaveResult = DataOperate.DataExecProc.DoDeleteSample(strSampleCode, ref strErrInfo);
                if (!bSaveResult)
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("删除试样编码{0}失败！原因：{1}", strSampleCode, strErrInfo));
                }
                else
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Run, string.Format("删除试样编码{0}成功！", strSampleCode));
                }
            }
            FormHelper.ApplicationShow(ricMsg, DisplayType.Process, "执行完毕，谢谢！");
            DoQuery("Delete");
        }

        /// <summary>
        /// 打印预览
        /// </summary>
        private void DoPrintView()
        {
            if (_listSelectRow.Count < 1)
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "请在查询出来的数据表中，勾选需要打印的行在点击打印预览按钮，谢谢！");
                return;
            }
            if (_listSelectRow.Count > 1)
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "只能选择一行数据进行预览，请重新选择,谢谢！");
                return;
            }
            var ultraGridRow = _listSelectRow[0];
            var strSampleCode = ultraGridRow.Cells["SAMPLE_CODE"].Value.ToString();
            var strCollectCode = ultraGridRow.Cells["COLLECT_CODE"].Value.ToString();
            var strType = ultraGridRow.Cells["SAMPLE_TYPE_STR"].Value.ToString();

            frmView obj = new frmView(strSampleCode, strSampleCode, strType, "0", _iPrintTestCodeNum, "", _iPrintBarcodeType);
            obj.ShowDialog();
        }

        /// <summary>
        /// 批量打印
        /// </summary>
        private void DoPrintAll()
        {
            if (_listSelectRow.Count < 1)
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "请在查询出来的数据表中，勾选需要打印的行在点击批量打印按钮，谢谢！");
                return;
            }
            foreach (var row in _listSelectRow)
            {
                string strCollectCode = row.Cells["COLLECT_CODE"].Value.ToString();
                string strSampleCode = row.Cells["SAMPLE_CODE"].Value.ToString();
                var strType = row.Cells["SAMPLE_TYPE_STR"].Value.ToString();
                DoPrint(strCollectCode, strSampleCode, strType);
            }
            FormHelper.ApplicationShow(ricMsg, DisplayType.Run, "批量打印完毕，谢谢！");
        }

        /// <summary>
        /// 打印标签
        /// </summary>
        /// <param name="strCollectCode">分样号</param>
        /// <param name="strSampleCode">样品编码</param>
        /// <param name="strType">样品类型 S3-S6-S2</param>
        private void DoPrint(string strCollectCode, string strSampleCode, string strType)
        {
            System.Drawing.Image img;
            if (_iPrintBarcodeType == 1)
            {
                var gen = new TagGen();
                img = gen.GetImgASample(strType, strSampleCode, _iPrintTestCodeNum);
                strType = strCollectCode + "_" + strType;
            }
            else
            {
                var strDesc = "";
                var strDescSize = strDesc.Length <= 2 ? "60" : (strDesc.Length * 2 * 10).ToString();
                img = Barcode.TwoDimensionBarcode.Encode(QRCodeEncoder.ENCODE_MODE.BYTE, QRCodeEncoder.ERROR_CORRECTION.M, "4", "7", strSampleCode, "", strDesc, strDescSize);
            }
            img = Barcode.TwoDimensionBarcode.CombinImageFloor(img, strType, 19, 60);
            var obj = new TagPrint(img, _iPrintBarcodeType);
            if (!obj.Print())
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("打印标签号{0}失败!", strSampleCode));
            }
            else
            {
                var strErrInfo = string.Empty;
                var bSaveResult = DataOperate.DataExecProc.DoUpdatePrintCount(strSampleCode, "0", ref strErrInfo);
                if (!bSaveResult)
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("更新样品编码{0}打印次数失败！请检查网络后重试", strSampleCode));
                }
                else
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Run, string.Format("打印样品编码{0}完毕，谢谢！", strSampleCode));
            }
        }
        /// <summary>
        /// 打印标签
        /// </summary>
        /// <param name="strHCode">样品编码</param>
        private void DoPrintMt(string strCollectCode, string strHCode)
        {
            System.Drawing.Image img;
            if (_iPrintBarcodeType == 1)
            {
                var gen = new TagGen();
                img = gen.GetImgASample("13mm", strHCode, _iPrintTestCodeNum);
            }
            else
            {
                var strDesc = "";
                var strDescSize = strDesc.Length <= 2 ? "60" : (strDesc.Length * 2 * 10).ToString();
                img = Barcode.TwoDimensionBarcode.Encode(QRCodeEncoder.ENCODE_MODE.BYTE, QRCodeEncoder.ERROR_CORRECTION.M, "4", "7", strHCode, "", strDesc, strDescSize);
            }
            img = Barcode.TwoDimensionBarcode.CombinImageFloor(img, "水分化验码", 12, 60);
            var obj = new TagPrint(img, _iPrintBarcodeType);
            if (!obj.Print())
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("打印标签号{0}失败!", strHCode));
            }
            else
            {
                var strErrInfo = string.Empty;
                var bSaveResult = DataOperate.DataExecProc.DoUpdatePrintCount(strHCode, "1", ref strErrInfo);
                if (!bSaveResult)
                {
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("更新水分化验编码{0}打印次数失败！请检查网络后重试", strHCode));
                }
                else
                    FormHelper.ApplicationShow(ricMsg, DisplayType.Run, string.Format("打印水分化验编码{0}完毕，谢谢！", strHCode));
            }
        }

        /// <summary>
        /// 打印收样编码
        /// </summary>
        private void DoPrintCode()
        {
            if (string.IsNullOrEmpty(txtCode.Text.Trim()))
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "请输入收样编码!");
                return;
            }
            var code = txtCode.Text.Trim();
            try
            {
                int i; int.TryParse(code, out i);
                switch (code.Length)
                {
                    case 1:
                        break;
                    case 2:
                        break;
                    case 6:
                        break;
                    case 8:
                        break;
                    case 9:
                        break;
                    default:
                        FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "收样号输入错误，请重新输入");
                        return;
                }
            }
            catch
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, "收样号输入异常，请重新输入!");
                return;
            }

            var gen = new TagGen();
            var img = gen.GetImgASample(code + "号样");
            var obj = new TagPrint(img, 1);
            if (!obj.Print())
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("打印标签号{0}失败!", txtCode.Text.Trim()));
            }
        }

        private void DoPrintCode(string code, string batchCode)
        {
            var gen = new TagGen();
            var img = gen.GetImgASample(code, batchCode);
            var obj = new TagPrint(img, 1);
            if (!obj.Print())
            {
                FormHelper.ApplicationShow(ricMsg, DisplayType.Error, string.Format("打印标签号{0}失败!", code));
            }
        }



        private void txtCode_Click(object sender, EventArgs e)
        {
            txtCode.Text = "";
        }
    }
}

